import pickle

class RPCProxy:
    '''为了从一个远程客户端访问服务器，你需要创建一个对应的用来传送请求的RPC代理类'''
    def __init__(self, connection):
        self._connection = connection
    def __getattr__(self, name):
        '''闭包'''
        def do_rpc(*args, **kwargs):
            self._connection.send(pickle.dumps((name, args, kwargs)))
            result = pickle.loads(self._connection.recv())
            if isinstance(result, Exception):
                raise result
            return result
        return do_rpc
    
'''要使用这个代理类，你需要将其包装到一个服务器的连接上面'''

from multiprocessing.connection import Client
c = Client(('localhost', 20001), authkey=b'peekaboo')
proxy = RPCProxy(c)
print(f"{proxy.add(2, 3) = }")
print(f"{proxy.sub(2, 3) = }")

try:
    proxy.sub([1, 2], 4)
except TypeError as e:
    print(e)  
